package tecpointbenchmark.model.modules;

import java.util.Date;
import tecpointbenchmark.model.dto.ResultDTO;

/**
 * @author Linus & Patrik 
 * 
 * Starts 2 threads making float calculations and keeps track of how many times they
 * are completed.
 */
public class MultiThreadFloatModule extends BenchmarkModule {

    private long score = 0;

    /**
     * Creates a new object with the resultDTO to save the result into.
     * @param r The result to where the benchmark is saving his info.
     */
    public MultiThreadFloatModule(ResultDTO r) {
        super(r);
        super.setModuleName("CPU Multi-thread Float");
        super.setShortDescription("Performs a floating point benchmark on the CPU");
        super.setLongDescription("Performs a floating test on the CPU by adding "
                + "arrays containing float values using multiple threads");
    }

    /**
     * Increase score by 100.
     */
    public void setScore() {
        score = score + 100;
    }

    /**
     * Runs the benchmark
     */
    @Override
    public void runBenchmark() {
        // Fetch the result object
        ResultDTO result = super.getResult();

        // Allow benchmarking
        super.setContinueBenchmarking(true);

        result.setTime(new Date().getTime());

        // Set the result to ERROR(2)
        result.setNumber(2);

        // The boolean variable 'continueBenchmarking' will remain true until
        // the handler changes it's value.

        FloatThread ft1 = new FloatThread(this);
        FloatThread ft2 = new FloatThread(this);

        Thread t1 = new Thread(ft1);
        Thread t2 = new Thread(ft2);



        t1.start();
        t2.start();

        long start = System.currentTimeMillis();

        while (super.getContinueBenchmarking()) {
            //sleep so this thread wont take all the cpu's resources
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();
        float time = (end - start) / 1000f;

        ft1.setContinueBenchmarking(false);
        ft2.setContinueBenchmarking(false);

        result.setMessage("Number of FLOPS: " + score + " (multithreading)");
        result.setPoints((int)(score/1000000*3*(5 / time)));
        if (tecpointbenchmark.startup.Main.debug) {
            System.out.println(result.getMessage());
            System.out.println("Module closing.");
        }
    }
}
